package com.basic.emg.utils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {


    //上传文件
    public static String uploadMeterImg(String baseDir, MultipartFile uploadfile)
            throws FileSizeLimitExceededException, IOException
    {

        String originalFilename = uploadfile.getOriginalFilename();
        int fileNamelength = originalFilename.length();
        if (fileNamelength > 100)
        {
            throw new RuntimeException("文件名过长");
        }

        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//当前时间

        String extension = FilenameUtils.getExtension(originalFilename);
        Date now = new Date();
//        String format0 = DateFormatUtils.format(now, "yyyy-MM-dd");
        String format2 = DateFormatUtils.format(now.getTime(), "yyyyMMddHHmmss");
        String fileName = File.separator + format2 + File.separator + originalFilename;
        System.out.println("fileName:--------------------" + fileName);

        //File desc = getAbsoluteFile(baseDir, fileName);
        File desc = new File(baseDir + File.separator + fileName);
        //File desc = new File( "H:/a.jpg");
        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        System.out.println("desc:---------------" + desc.getAbsolutePath());

        uploadfile.transferTo(desc);
        //f.deleteOnExit();
        return fileName;

    }
}
